package com.platform.modules.wallet.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.platform.common.constant.AppConstants;
import com.platform.common.exception.BaseException;
import com.platform.common.shiro.ShiroUtils;
import com.platform.common.shiro.utils.Md5Utils;
import com.platform.common.utils.redis.RedisUtils;
import com.platform.common.version.ApiVersion;
import com.platform.common.version.VersionEnum;
import com.platform.common.web.controller.BaseController;
import com.platform.common.web.domain.AjaxResult;
import com.platform.modules.chat.domain.ChatUser;
import com.platform.modules.chat.service.ChatUserService;
import com.platform.modules.wallet.domain.Wallet;
import com.platform.modules.wallet.domain.WalletTransfer;
import com.platform.modules.wallet.enums.AccountTypeEnum;
import com.platform.modules.wallet.service.WalletAccountService;
import com.platform.modules.wallet.service.WalletKPayService;
import com.platform.modules.wallet.service.WalletRechargeCashService;
import com.platform.modules.wallet.service.WalletService;
import com.platform.modules.wallet.utils.TransferUtils;
import com.platform.modules.wallet.vo.RechargeCashVo01;
import com.platform.modules.wallet.vo.WalletVo01;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * 钱包
 */
@RestController
@Slf4j
@RequestMapping("/wallet")
public class WalletController extends BaseController {


    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private WalletService walletService;
    @Resource
    private WalletRechargeCashService walletRechargeCashService;
    @Resource
    private ChatUserService chatUserService;
    @Resource
    private WalletAccountService walletAccountService;
    @Autowired
    private TransferUtils transferUtils;
    @Autowired
    private WalletKPayService walletKPayService;

    /**
     * 获取钱包信息
     */
    @ApiVersion(VersionEnum.V1_0_0)
    @GetMapping("/getWallet")
    public AjaxResult getWallet() {
        Long userId = ShiroUtils.getUserId();
        Wallet wallet = walletService.getWallet(userId);

        return AjaxResult.success(BeanUtil.toBean(wallet, WalletVo01.class));
    }

    /**
     * 获取钱包余额
     */
    @ApiVersion(VersionEnum.V1_0_0)
    @GetMapping("/getBalance")
    public AjaxResult getBalance() {
        Long userId = ShiroUtils.getUserId();
        return AjaxResult.success(walletService.getBalance(userId));
    }

    /**
     * 我的账本记录
     */
    @ApiVersion(VersionEnum.V1_0_0)
    @GetMapping("/getMyAccount")
    public AjaxResult getMyAccount(@RequestParam Integer page) {
        Long userId = ShiroUtils.getUserId();
        return AjaxResult.success(walletAccountService.queryByUserId(userId, page));
    }

    /**
     * 存取
     */
    @ApiVersion(VersionEnum.V1_0_0)
    @PostMapping("/doRechargeCash")
    public AjaxResult doRechargeCash(@Validated @RequestBody RechargeCashVo01 vo01) {


        Long userId = ShiroUtils.getUserId();
        // 当前用户
        ChatUser cu = chatUserService.getById(userId);
        Wallet wallet = walletService.getWallet(userId);

        //元转换为分
        int amount = vo01.getMoney().multiply(BigDecimal.valueOf(100)).intValue();
        vo01.setAmount(Integer.valueOf(amount));
        vo01.setUserId(userId);

        String lock_key = AppConstants.LOCK_PREFIX + "rechargecash:" + wallet.getUserId();
        if (redisUtils.hasKey(lock_key)) {
            throw new BaseException("操作太频繁，请稍后再试");
        }

        redisUtils.set(lock_key, wallet.getUserId().toString(), AppConstants.LOCK_EXPIRE, TimeUnit.SECONDS);

        if (vo01.getType().equals(AccountTypeEnum.CASH)) {

            if (StrUtil.isBlank(wallet.getPayPassword())) {
                return AjaxResult.fail("提现失败：支付密码未设置");
            }

            String payPassword = Md5Utils.credentials(vo01.getPayPassword(), cu.getSalt());
            if (!payPassword.equalsIgnoreCase(wallet.getPayPassword())) {
                return AjaxResult.fail("提现失败：密码验证有误");
            }

            if (walletService.getBalance(wallet.getUserId()) < vo01.getAmount().intValue()) {
                return AjaxResult.fail("失败：提现金额超出余额");
            }
        }

        if (StrUtil.isBlank(wallet.getPayPassword())) {
            return AjaxResult.fail("提现失败：支付密码未设置");
        }

        int maxCashAmount = 2000000;
        if (vo01.getAmount().intValue() > maxCashAmount) {
            return AjaxResult.fail("失败：金额超出" + maxCashAmount / 100);
        }

        transferUtils.verifyAccount();

        walletRechargeCashService.createRechargeCash(vo01);

        redisUtils.expire(lock_key, AppConstants.LOCK_END, TimeUnit.SECONDS);

        return AjaxResult.success("提现订单创建成功");
    }

    /**
     * 登入钱包
     */
    @ApiVersion(VersionEnum.V1_0_0)
    @GetMapping("/doLogin")
    public AjaxResult doLogin() {

        Long userId = ShiroUtils.getUserId();
        Wallet wallet = walletService.getWallet(userId);

        return AjaxResult.success(walletKPayService.login(wallet.getWalletAddress()));
    }
}
